<?php
/**
 * Created by PhpStorm
 * User: lcz
 * Date: 2019/9/10
 * Time: 22:30
 * 订单
 */

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\log\Log;
use app\common\library\Weixin;
use app\common\model\OrderShipping;
use app\common\model\RedEnvelope;
use app\common\validate\Invoice;
use think\Db;
use think\Exception;

class Order extends Api
{
	protected $noNeedLogin = ['notify'];
	
	/**
	 * 列表
	 */
	public function index()
	{
		$userId = $this->auth->id;
		$page = $this->request->post('page', 1, 'int');
		$status = $this->request->post('status', '', 'int');
		$type = $this->request->post('type', '', 'int');
		
		$model = new \app\common\model\Order();
		$res = $model->getOrderList($userId, $page, $status, $type);
		$this->success('查询成功', $res);
	}
	
	/**
	 * 详情
	 */
	public function detail()
	{
		$id = $this->request->post('id');
		!$id && $this->error('参数错误');
		
		$model = new \app\common\model\Order();
		$order = $model->where(['user_id' => $this->auth->id, 'id' => $id])->find();
		!$order && $this->error('订单不存在');
		
		$goods = Db::name('orderGoods')
			->where(['order_id' => $id])
			->find();
		
		$goods['goods_info'] = json_decode($goods['goods_info'], true);
		
		$order['goods'] = [$goods];
		
		$order['groupInfo'] = null;
		
		if($order['group_id']) {
			$groupWhere['o.group_id'] = $order['group_id'];
			$groupInfo = Db::name('orderGroup')->find($order['group_id']);
			$users = Db::name('order')->alias('o')
				->join('user u', 'o.user_id = u.id', 'left')
				->where($groupWhere)
				->order(['o.create_time' => 'ASC'])
				->column('avatar', 'user_id');
			
			$groupInfo['user'] = array_values($users);
			$order['groupInfo'] = $groupInfo;

		}
		
		$this->success('查询成功', $order);
	}
	
	/**
	 * 确认订单
	 */
	public function confirm()
	{
		$model = new \app\common\model\Order();
		$userId = $this->auth->id;
		$res = $model->addOrder($userId, $this->request->post(), 1);
		if (!$res) {
			$this->error($model->getError());
		}
		
		$this->success('成功', $res);
	}
	
	/**
	 * 下单
	 */
	public function add()
	{
		$model = new \app\common\model\Order();
		$userId = $this->auth->id;
		$res = $model->addOrder($userId, $this->request->post(), 2);
		if (!$res) {
			$this->error($model->getError());
		}
		
		$config = config('weixin.' . $this->weixinPrefix);
		$weixin = new Weixin($config['app_id']);
		
		$notifyUrl = $this->request->domain() . url('api/notify/order', '', false);
		$user = \app\admin\model\User::get($userId);
		$openId = $user[$this->weixinPrefix . '_openid'];
		$data = $weixin->unifiedOrder($res['id'], $res['amount'], $notifyUrl, $openId);
		$data['data']['id'] = $res['id'];
		$this->success($data['msg'], $data['data'], $data['code']);
	}
	
	/**
	 * 支付
	 */
	public function pay()
	{
		$id = $this->request->post('id');
		!$id && $this->error('参数错误');
		
		$userId = $this->auth->id;
		$order = \app\common\model\Order::get($id);
		!$order && $this->error('订单不存在');
		if ($order['status'] != \app\common\model\Order::STATUS_WAIT) {
			$this->error('非待支付订单');
		}
		
		$config = config('weixin.' . $this->weixinPrefix);
		$weixin = new Weixin($config['app_id']);
		
		$notifyUrl = $this->request->domain() . url('api/notify/order', '', false);
		$user = \app\admin\model\User::get($userId);
		$openId = $user[$this->weixinPrefix . '_openid'];
		$data = $weixin->unifiedOrder($id, $order['amount'], $notifyUrl, $openId);
		$this->success($data['msg'], $data['data'], $data['code']);
	}
	
	/**
	 * 取消
	 */
	public function cancel()
	{
		$id = $this->request->post('id');
		!$id && $this->error('参数错误');
		
		$userId = $this->auth->id;
		
		$model = new \app\common\model\Order();
		$res = $model->cancel($id, $model::CANCEL_REASON_USER, $userId);
		if ($res !== false) {
			$this->success('取消成功');
		} else {
			$this->error('取消出错');
		}
	}
	
	/**
	 * 删除
	 */
	public function del()
	{
		$id = $this->request->post('id');
		!$id && $this->error('参数错误');
		
		$userId = $this->auth->id;
		
		$model = new \app\common\model\Order();
		$order = $model->where(['id' => $id, 'user_id' => $userId])->find();
		!$order && $this->error('订单不存在');
		
		$res = $model->save(['is_delete' => 1],
			['id' => $id]);
		if ($res !== false) {
			$this->success('删除成功');
		} else {
			$this->error('删除出错');
		}
	}
	
	/**
	 * 物流
	 */
	public function shipping()
	{
		$id = $this->request->post('id');
		!$id && $this->error('参数错误');
		
		$model = new OrderShipping();
		$res = $model->getShipping($id);
		$data = $res['Traces'] ??[];
		$this->success('查询成功', $data);
	}
	
	
	/**
	 * 签收
	 */
	public function sign()
	{
		$id = $this->request->post('id');
		!$id && $this->error('参数错误');
		
		$model = new \app\common\model\Order();
		$userId = $this->auth->id;
		
		$res = $model->sign($id, $userId);
		if ($res) {
			$this->success('签收成功');
		} else {
			$this->error('签收出错');
		}
	}
	
	/**
	 * 红包
	 */
	public function hb() {
		$orderId = $this->request->post('order_id');
		$row = Db::name('redEnvelope')->where(['order_id' => $orderId, 'user_id' => $this->auth->id])
			->find();
		if($row) {
			$this->success('查询成功', $row);
		} else {
			$this->error('红包不存在');
		}
	}
	
	
	/**
	 * 领取红包
	 */
	public function receiveHb() {
		$orderId = $this->request->post('order_id');
		!$orderId && $this->error('参数错误');
		
		$model = new RedEnvelope();
		$res = $model->receive($this->auth->id, $orderId);
		if($res) {
			$this->success('领取成功');
		} else {
			$this->error($model->getError());
		}
	}
	
	
	/**
	 * 开发票
	 */
	public function invoice() {
		$data = $this->request->post();
		$check = new Invoice();
		if(!$check->check($data)) {
			$this->error($check->getError());
		}
		
		if($data['type'] == 1 && (!isset($data['no']) || !$data['no'])) {
			$this->error('税号不能为空');
		}
		$userId = $this->auth->id;
		$order = \app\common\model\Order::get(['id' => $data['order_id'], 'user_id' => $userId]);
		!$order && $this->error('订单不存在');
		
		if($order['pay_status'] != \app\common\model\Order::PAY_STATUS_Y) {
			$this->error('订单未付款');
		}
		
		if($order['invoice_status'] != 0) {
			$this->error('该订单已经开过了');
		}
		
		$model = new \app\common\model\Invoice();
		$model->startTrans();
		try {
			$orderRes = Db::name('order')->where(['id' => $order['id']])->update(['invoice_status' => 1]);
			if(!$orderRes) {
				throw new Exception('更改订单发票状态出错');
			}
			
			$data['user_id'] = $userId;
			$res = $model->isUpdate(false)->allowField(true)->save($data);
			if(!$res) {
				throw new Exception('添加发票信息出错');
			}
			
			$model->commit();
			$this->success('申请成功');
		} catch (Exception $e) {
			$model->rollback();
			$this->error($model->getError());
		}
	}
}